#include <QSpinBox>
#include "spin-box-delegate.h"

SpinBoxDelegate::SpinBoxDelegate (QObject *parent) :
    QStyledItemDelegate(parent), m_oldValue(0), m_rangeStart(0), m_rangeEnd(1000000), m_defaultValue(0)
{
}

QWidget* SpinBoxDelegate::createEditor (QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    Q_UNUSED(option);
    Q_UNUSED(index);
    QSpinBox* spinBox = new QSpinBox(parent);
    spinBox->setRange(m_rangeStart, m_rangeEnd);
    spinBox->setValue(m_defaultValue);
    return spinBox;
}

void SpinBoxDelegate::setEditorData (QWidget* editor, const QModelIndex& index) const
{
    int value = index.data(Qt::UserRole).toInt();
    m_oldValue = value;

    QSpinBox* spinBox = static_cast<QSpinBox*>(editor);
    spinBox->setValue(value);
}

void SpinBoxDelegate::setModelData (QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
    QSpinBox* spinBox = static_cast<QSpinBox*>(editor);

    int newValue = spinBox->value();
    if (newValue == m_oldValue)
        return;

    model->setData(index, newValue, Qt::UserRole);
}

void SpinBoxDelegate::setRange(int rangeStart, int rangeEnd)
{
    m_rangeStart = rangeStart;
    m_rangeEnd = rangeEnd;
}

void SpinBoxDelegate::setDefaultValue(int defaultValue)
{
    m_defaultValue = defaultValue;
}
